/*!
 * \file test_wt_engines_comprehensive.cpp
 * \project WonderTrader
 * 
 * \brief WonderTrader核心引擎类综合测试
 * 
 * \details 本文件包含对WonderTrader核心引擎类的全面测试，包括：
 *          - WtEngine基础引擎测试
 *          - WtCtaEngine CTA引擎测试  
 *          - WtHftEngine HFT引擎测试
 *          - WtSelEngine SEL引擎测试
 *          - WtUftEngine UFT引擎测试
 *          - 引擎初始化和配置测试
 *          - 行情数据处理测试
 *          - 交易信号处理测试
 *          - 风险管理测试
 *          - 性能基准测试
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <memory>
#include <thread>
#include <chrono>

// WonderTrader核心引擎头文件
#include "../../src/WtCore/WtEngine.h"
#include "../../src/WtCore/WtCtaEngine.h"
#include "../../src/WtCore/WtHftEngine.h"
#include "../../src/WtCore/WtSelEngine.h"
#include "../../src/WtUftCore/WtUftEngine.h"

// 依赖组件头文件
#include "../../src/WtCore/WtDtMgr.h"
#include "../../src/WtCore/EventNotifier.h"
#include "../../src/WTSTools/WTSBaseDataMgr.h"
#include "../../src/WTSTools/WTSHotMgr.h"
#include "../../src/Includes/WTSVariant.hpp"
#include "../../src/Includes/WTSDataDef.hpp"
#include "../../src/WTSTools/WTSLogger.h"

using namespace WTSTP;
using ::testing::_;
using ::testing::Return;
using ::testing::StrictMock;
using ::testing::NiceMock;

// ============================================================================
// Mock类定义
// ============================================================================

/*!
 * \class MockEngineEventListener
 * \brief 引擎事件监听器Mock类
 */
class MockEngineEventListener : public IEngineEvtListener
{
public:
    MOCK_METHOD0(on_initialize_event, void());
    MOCK_METHOD2(on_schedule_event, void(uint32_t uDate, uint32_t uTime));
    MOCK_METHOD2(on_session_event, void(uint32_t uDate, bool isBegin));
};

/*!
 * \class MockBaseDataMgr
 * \brief 基础数据管理器Mock类
 */
class MockBaseDataMgr : public IBaseDataMgr
{
public:
    MOCK_METHOD2(getContract, WTSContractInfo*(const char* code, const char* exchg));
    MOCK_METHOD1(getCommodity, WTSCommodityInfo*(const char* stdCode));
    MOCK_METHOD1(getSession, WTSSessionInfo*(const char* sid));
    MOCK_METHOD0(getSessionCount, uint32_t());
    MOCK_METHOD1(getSessionByIndex, WTSSessionInfo*(uint32_t idx));
    MOCK_METHOD1(getTradingSession, WTSSessionInfo*(const char* stdCode));
    MOCK_METHOD1(getAuctionSession, WTSSessionInfo*(const char* stdCode));
    MOCK_METHOD1(isHoliday, bool(const char* stdCode, uint32_t uDate, bool isTpl));
    MOCK_METHOD0(release, void());
};

/*!
 * \class MockHotMgr
 * \brief 热点管理器Mock类
 */
class MockHotMgr : public IHotMgr
{
public:
    MOCK_METHOD3(getHotContract, const char*(const char* stdCode, uint32_t dt, bool bNext));
    MOCK_METHOD2(getPrevRawCode, const char*(const char* stdCode, uint32_t dt));
    MOCK_METHOD2(getRawCode, const char*(const char* stdCode, uint32_t dt));
    MOCK_METHOD1(splitHotSecions, bool(const char* stdCode));
    MOCK_METHOD0(release, void());
};

/*!
 * \class TestableWtEngine
 * \brief 可测试的WtEngine派生类
 */
class TestableWtEngine : public WtEngine
{
public:
    TestableWtEngine() : WtEngine() {}
    
    // 实现纯虚函数
    virtual void run(bool bAsync = false) override {
        _ready = true;
        if (!bAsync) {
            // 模拟同步运行
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
        }
    }
    
    virtual void on_bar(const char* stdCode, const char* period, uint32_t times, WTSBarStruct* newBar) override {
        // 模拟K线处理
        if (newBar) {
            _last_bar_code = stdCode;
            _last_bar_time = newBar->time;
        }
    }
    
    // 测试辅助方法
    bool isReady() const { return _ready; }
    const std::string& getLastBarCode() const { return _last_bar_code; }
    uint64_t getLastBarTime() const { return _last_bar_time; }
    
    // 暴露受保护的方法用于测试
    void test_append_signal(const char* stdCode, double qty, bool bStandBy = false) {
        append_signal(stdCode, qty, bStandBy);
    }
    
    void test_do_set_position(const char* stdCode, double qty, double curPx = -1) {
        do_set_position(stdCode, qty, curPx);
    }

private:
    std::string _last_bar_code;
    uint64_t _last_bar_time = 0;
};

// ============================================================================
// WtEngine基础引擎测试套件
// ============================================================================

class WtEngineTest : public ::testing::Test
{
protected:
    void SetUp() override {
        // 初始化日志系统
        WTSLogger::init("test_logs/", true);
        
        // 创建测试对象
        engine = std::make_unique<TestableWtEngine>();
        mockBdMgr = std::make_unique<NiceMock<MockBaseDataMgr>>();
        mockHotMgr = std::make_unique<NiceMock<MockHotMgr>>();
        dataMgr = std::make_unique<WtDtMgr>();
        notifier = std::make_unique<EventNotifier>();
        
        // 创建测试配置
        config = WTSVariant::createObject();
        config->append("name", "test_engine", false);
        config->append("mode", "product", false);
        
        // 设置Mock默认行为
        ON_CALL(*mockBdMgr, getContract(_, _))
            .WillByDefault(Return(nullptr));
        ON_CALL(*mockHotMgr, getHotContract(_, _, _))
            .WillByDefault(Return("SHFE.rb2401"));
    }
    
    void TearDown() override {
        if (config) {
            config->release();
            config = nullptr;
        }
        WTSLogger::stop();
    }

protected:
    std::unique_ptr<TestableWtEngine> engine;
    std::unique_ptr<MockBaseDataMgr> mockBdMgr;
    std::unique_ptr<MockHotMgr> mockHotMgr;
    std::unique_ptr<WtDtMgr> dataMgr;
    std::unique_ptr<EventNotifier> notifier;
    WTSVariant* config = nullptr;
};

/*!
 * \brief 测试WtEngine基本构造和析构
 */
TEST_F(WtEngineTest, TestBasicConstruction)
{
    EXPECT_NE(engine.get(), nullptr);
    EXPECT_FALSE(engine->isReady());
}

/*!
 * \brief 测试WtEngine初始化功能
 */
TEST_F(WtEngineTest, TestEngineInitialization)
{
    // 测试正常初始化
    EXPECT_NO_THROW({
        engine->init(config, mockBdMgr.get(), dataMgr.get(), mockHotMgr.get(), notifier.get());
    });
    
    // 测试空配置初始化
    EXPECT_NO_THROW({
        engine->init(nullptr, mockBdMgr.get(), dataMgr.get(), mockHotMgr.get(), notifier.get());
    });
}

/*!
 * \brief 测试WtEngine运行功能
 */
TEST_F(WtEngineTest, TestEngineRun)
{
    engine->init(config, mockBdMgr.get(), dataMgr.get(), mockHotMgr.get(), notifier.get());
    
    // 测试同步运行
    EXPECT_NO_THROW({
        engine->run(false);
    });
    EXPECT_TRUE(engine->isReady());
    
    // 测试异步运行
    EXPECT_NO_THROW({
        engine->run(true);
    });
}

/*!
 * \brief 测试WtEngine tick数据处理
 */
TEST_F(WtEngineTest, TestTickDataProcessing)
{
    engine->init(config, mockBdMgr.get(), dataMgr.get(), mockHotMgr.get(), notifier.get());
    
    // 创建测试tick数据
    WTSTickData* tick = WTSTickData::create("SHFE.rb2401");
    tick->setPrice(4000.0);
    tick->setVolume(100);
    tick->setActionDate(20241201);
    tick->setActionTime(93000000);
    
    // 测试tick处理
    EXPECT_NO_THROW({
        engine->on_tick("SHFE.rb2401", tick);
    });
    
    tick->release();
}

/*!
 * \brief 测试WtEngine K线数据处理
 */
TEST_F(WtEngineTest, TestBarDataProcessing)
{
    engine->init(config, mockBdMgr.get(), dataMgr.get(), mockHotMgr.get(), notifier.get());
    
    // 创建测试K线数据
    WTSBarStruct bar;
    bar.date = 20241201;
    bar.time = 202412010930;
    bar.open = 4000.0;
    bar.high = 4010.0;
    bar.low = 3990.0;
    bar.close = 4005.0;
    bar.vol = 1000;
    bar.money = 4005000.0;
    bar.hold = 50000;
    bar.add = 100;
    
    // 测试K线处理
    EXPECT_NO_THROW({
        engine->on_bar("SHFE.rb2401", "m1", 1, &bar);
    });
    
    EXPECT_EQ(engine->getLastBarCode(), "SHFE.rb2401");
    EXPECT_EQ(engine->getLastBarTime(), bar.time);
}

/*!
 * \brief 测试WtEngine信号处理
 */
TEST_F(WtEngineTest, TestSignalProcessing)
{
    engine->init(config, mockBdMgr.get(), dataMgr.get(), mockHotMgr.get(), notifier.get());
    
    // 测试追加信号
    EXPECT_NO_THROW({
        engine->test_append_signal("SHFE.rb2401", 10.0, false);
        engine->test_append_signal("SHFE.rb2401", -5.0, true);
    });
}

/*!
 * \brief 测试WtEngine持仓设置
 */
TEST_F(WtEngineTest, TestPositionSetting)
{
    engine->init(config, mockBdMgr.get(), dataMgr.get(), mockHotMgr.get(), notifier.get());
    
    // 测试设置持仓
    EXPECT_NO_THROW({
        engine->test_do_set_position("SHFE.rb2401", 10.0, 4000.0);
        engine->test_do_set_position("SHFE.rb2401", 0.0);  // 平仓
    });
}

/*!
 * \brief 测试WtEngine会话事件处理
 */
TEST_F(WtEngineTest, TestSessionEvents)
{
    engine->init(config, mockBdMgr.get(), dataMgr.get(), mockHotMgr.get(), notifier.get());
    
    // 测试会话开始和结束
    EXPECT_NO_THROW({
        engine->on_session_begin();
        engine->on_session_end();
    });
}

// ============================================================================
// WtCtaEngine CTA引擎测试套件
// ============================================================================

class WtCtaEngineTest : public ::testing::Test
{
protected:
    void SetUp() override {
        WTSLogger::init("test_logs/", true);
        
        ctaEngine = std::make_unique<WtCtaEngine>();
        mockBdMgr = std::make_unique<NiceMock<MockBaseDataMgr>>();
        mockHotMgr = std::make_unique<NiceMock<MockHotMgr>>();
        dataMgr = std::make_unique<WtDtMgr>();
        notifier = std::make_unique<EventNotifier>();
        
        config = WTSVariant::createObject();
        config->append("name", "cta", false);
        config->append("mode", "product", false);
    }
    
    void TearDown() override {
        if (config) {
            config->release();
            config = nullptr;
        }
        WTSLogger::stop();
    }

protected:
    std::unique_ptr<WtCtaEngine> ctaEngine;
    std::unique_ptr<MockBaseDataMgr> mockBdMgr;
    std::unique_ptr<MockHotMgr> mockHotMgr;
    std::unique_ptr<WtDtMgr> dataMgr;
    std::unique_ptr<EventNotifier> notifier;
    WTSVariant* config = nullptr;
};

/*!
 * \brief 测试CTA引擎基本功能
 */
TEST_F(WtCtaEngineTest, TestCtaEngineBasics)
{
    EXPECT_NE(ctaEngine.get(), nullptr);
    
    // 测试初始化
    EXPECT_NO_THROW({
        ctaEngine->init(config, mockBdMgr.get(), dataMgr.get(), mockHotMgr.get(), notifier.get());
    });
}

/*!
 * \brief 测试CTA引擎运行
 */
TEST_F(WtCtaEngineTest, TestCtaEngineRun)
{
    ctaEngine->init(config, mockBdMgr.get(), dataMgr.get(), mockHotMgr.get(), notifier.get());
    
    // 测试异步运行
    EXPECT_NO_THROW({
        ctaEngine->run(true);
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
    });
}

/*!
 * \brief 测试CTA引擎行情处理
 */
TEST_F(WtCtaEngineTest, TestCtaQuoteHandling)
{
    ctaEngine->init(config, mockBdMgr.get(), dataMgr.get(), mockHotMgr.get(), notifier.get());
    
    // 创建测试tick数据
    WTSTickData* tick = WTSTickData::create("SHFE.rb2401");
    tick->setPrice(4000.0);
    tick->setVolume(100);
    
    EXPECT_NO_THROW({
        ctaEngine->handle_push_quote(tick, 0);
        ctaEngine->on_tick("SHFE.rb2401", tick);
    });
    
    tick->release();
}

/*!
 * \brief 测试CTA引擎K线处理
 */
TEST_F(WtCtaEngineTest, TestCtaBarHandling)
{
    ctaEngine->init(config, mockBdMgr.get(), dataMgr.get(), mockHotMgr.get(), notifier.get());
    
    WTSBarStruct bar;
    bar.date = 20241201;
    bar.time = 202412010930;
    bar.open = 4000.0;
    bar.close = 4005.0;
    bar.vol = 1000;
    
    EXPECT_NO_THROW({
        ctaEngine->on_bar("SHFE.rb2401", "m1", 1, &bar);
    });
}

/*!
 * \brief 测试CTA引擎会话管理
 */
TEST_F(WtCtaEngineTest, TestCtaSessionManagement)
{
    ctaEngine->init(config, mockBdMgr.get(), dataMgr.get(), mockHotMgr.get(), notifier.get());
    
    EXPECT_NO_THROW({
        ctaEngine->on_init();
        ctaEngine->on_session_begin();
        ctaEngine->on_session_end();
    });
}

// ============================================================================
// WtHftEngine HFT引擎测试套件
// ============================================================================

class WtHftEngineTest : public ::testing::Test
{
protected:
    void SetUp() override {
        WTSLogger::init("test_logs/", true);
        
        hftEngine = std::make_unique<WtHftEngine>();
        mockBdMgr = std::make_unique<NiceMock<MockBaseDataMgr>>();
        mockHotMgr = std::make_unique<NiceMock<MockHotMgr>>();
        dataMgr = std::make_unique<WtDtMgr>();
        notifier = std::make_unique<EventNotifier>();
        
        config = WTSVariant::createObject();
        config->append("name", "hft", false);
        config->append("mode", "product", false);
    }
    
    void TearDown() override {
        if (config) {
            config->release();
            config = nullptr;
        }
        WTSLogger::stop();
    }

protected:
    std::unique_ptr<WtHftEngine> hftEngine;
    std::unique_ptr<MockBaseDataMgr> mockBdMgr;
    std::unique_ptr<MockHotMgr> mockHotMgr;
    std::unique_ptr<WtDtMgr> dataMgr;
    std::unique_ptr<EventNotifier> notifier;
    WTSVariant* config = nullptr;
};

/*!
 * \brief 测试HFT引擎基本功能
 */
TEST_F(WtHftEngineTest, TestHftEngineBasics)
{
    EXPECT_NE(hftEngine.get(), nullptr);
    
    EXPECT_NO_THROW({
        hftEngine->init(config, mockBdMgr.get(), dataMgr.get(), mockHotMgr.get(), notifier.get());
    });
}

/*!
 * \brief 测试HFT引擎高频数据处理
 */
TEST_F(WtHftEngineTest, TestHftHighFrequencyData)
{
    hftEngine->init(config, mockBdMgr.get(), dataMgr.get(), mockHotMgr.get(), notifier.get());
    
    // 创建高频tick数据
    WTSTickData* tick = WTSTickData::create("SHFE.rb2401");
    tick->setPrice(4000.0);
    tick->setVolume(1);
    tick->setActionTime(93000000);  // 高精度时间
    
    EXPECT_NO_THROW({
        hftEngine->handle_push_quote(tick, 1);  // 热点标志
        hftEngine->on_tick("SHFE.rb2401", tick);
    });
    
    tick->release();
}

/*!
 * \brief 测试HFT引擎Level2数据处理
 */
TEST_F(WtHftEngineTest, TestHftLevel2Data)
{
    hftEngine->init(config, mockBdMgr.get(), dataMgr.get(), mockHotMgr.get(), notifier.get());
    
    // 测试委托队列数据
    WTSOrdQueData* ordQue = WTSOrdQueData::create("SHFE.rb2401");
    if (ordQue) {
        EXPECT_NO_THROW({
            hftEngine->handle_push_order_queue(ordQue);
        });
        ordQue->release();
    }
    
    // 测试委托明细数据
    WTSOrdDtlData* ordDtl = WTSOrdDtlData::create("SHFE.rb2401");
    if (ordDtl) {
        EXPECT_NO_THROW({
            hftEngine->handle_push_order_detail(ordDtl);
        });
        ordDtl->release();
    }
    
    // 测试成交明细数据
    WTSTransData* trans = WTSTransData::create("SHFE.rb2401");
    if (trans) {
        EXPECT_NO_THROW({
            hftEngine->handle_push_transaction(trans);
        });
        trans->release();
    }
}

// ============================================================================
// WtSelEngine SEL引擎测试套件
// ============================================================================

class WtSelEngineTest : public ::testing::Test
{
protected:
    void SetUp() override {
        WTSLogger::init("test_logs/", true);
        
        selEngine = std::make_unique<WtSelEngine>();
        mockBdMgr = std::make_unique<NiceMock<MockBaseDataMgr>>();
        mockHotMgr = std::make_unique<NiceMock<MockHotMgr>>();
        dataMgr = std::make_unique<WtDtMgr>();
        notifier = std::make_unique<EventNotifier>();
        
        config = WTSVariant::createObject();
        config->append("name", "sel", false);
        config->append("mode", "product", false);
    }
    
    void TearDown() override {
        if (config) {
            config->release();
            config = nullptr;
        }
        WTSLogger::stop();
    }

protected:
    std::unique_ptr<WtSelEngine> selEngine;
    std::unique_ptr<MockBaseDataMgr> mockBdMgr;
    std::unique_ptr<MockHotMgr> mockHotMgr;
    std::unique_ptr<WtDtMgr> dataMgr;
    std::unique_ptr<EventNotifier> notifier;
    WTSVariant* config = nullptr;
};

/*!
 * \brief 测试SEL引擎基本功能
 */
TEST_F(WtSelEngineTest, TestSelEngineBasics)
{
    EXPECT_NE(selEngine.get(), nullptr);
    
    EXPECT_NO_THROW({
        selEngine->init(config, mockBdMgr.get(), dataMgr.get(), mockHotMgr.get(), notifier.get());
    });
}

/*!
 * \brief 测试SEL引擎选股功能
 */
TEST_F(WtSelEngineTest, TestSelEngineStockSelection)
{
    selEngine->init(config, mockBdMgr.get(), dataMgr.get(), mockHotMgr.get(), notifier.get());
    
    // 创建股票tick数据
    WTSTickData* tick = WTSTickData::create("SSE.600000");
    tick->setPrice(10.50);
    tick->setVolume(10000);
    
    EXPECT_NO_THROW({
        selEngine->on_tick("SSE.600000", tick);
    });
    
    tick->release();
}

// ============================================================================
// WtUftEngine UFT引擎测试套件
// ============================================================================

class WtUftEngineTest : public ::testing::Test
{
protected:
    void SetUp() override {
        WTSLogger::init("test_logs/", true);
        
        uftEngine = std::make_unique<WtUftEngine>();
        mockBdMgr = std::make_unique<NiceMock<MockBaseDataMgr>>();
        
        config = WTSVariant::createObject();
        config->append("name", "uft", false);
        config->append("mode", "product", false);
    }
    
    void TearDown() override {
        if (config) {
            config->release();
            config = nullptr;
        }
        WTSLogger::stop();
    }

protected:
    std::unique_ptr<WtUftEngine> uftEngine;
    std::unique_ptr<MockBaseDataMgr> mockBdMgr;
    WTSVariant* config = nullptr;
};

/*!
 * \brief 测试UFT引擎基本功能
 */
TEST_F(WtUftEngineTest, TestUftEngineBasics)
{
    EXPECT_NE(uftEngine.get(), nullptr);
    
    // 测试时间设置
    EXPECT_NO_THROW({
        uftEngine->set_date_time(20241201, 93000, 0, 93000);
        uftEngine->set_trading_date(20241201);
    });
}

/*!
 * \brief 测试UFT引擎超高频处理
 */
TEST_F(WtUftEngineTest, TestUftUltraHighFrequency)
{
    // 测试微秒级时间处理
    uint32_t curDate = 20241201;
    uint32_t curTime = 93000;
    uint32_t curSecs = 123456;  // 微秒级精度
    
    EXPECT_NO_THROW({
        uftEngine->set_date_time(curDate, curTime, curSecs, curTime);
    });
}

// ============================================================================
// 引擎性能基准测试
// ============================================================================

class EnginePerformanceTest : public ::testing::Test
{
protected:
    void SetUp() override {
        WTSLogger::init("test_logs/", true);
        
        engine = std::make_unique<TestableWtEngine>();
        mockBdMgr = std::make_unique<NiceMock<MockBaseDataMgr>>();
        mockHotMgr = std::make_unique<NiceMock<MockHotMgr>>();
        dataMgr = std::make_unique<WtDtMgr>();
        notifier = std::make_unique<EventNotifier>();
        
        config = WTSVariant::createObject();
        config->append("name", "perf_test", false);
        
        engine->init(config, mockBdMgr.get(), dataMgr.get(), mockHotMgr.get(), notifier.get());
    }
    
    void TearDown() override {
        if (config) {
            config->release();
            config = nullptr;
        }
        WTSLogger::stop();
    }

protected:
    std::unique_ptr<TestableWtEngine> engine;
    std::unique_ptr<MockBaseDataMgr> mockBdMgr;
    std::unique_ptr<MockHotMgr> mockHotMgr;
    std::unique_ptr<WtDtMgr> dataMgr;
    std::unique_ptr<EventNotifier> notifier;
    WTSVariant* config = nullptr;
};

/*!
 * \brief 测试引擎tick处理性能
 */
TEST_F(EnginePerformanceTest, TestTickProcessingPerformance)
{
    const int TICK_COUNT = 10000;
    
    auto start = std::chrono::high_resolution_clock::now();
    
    for (int i = 0; i < TICK_COUNT; ++i) {
        WTSTickData* tick = WTSTickData::create("SHFE.rb2401");
        tick->setPrice(4000.0 + i * 0.1);
        tick->setVolume(100 + i);
        tick->setActionTime(93000000 + i);
        
        engine->on_tick("SHFE.rb2401", tick);
        tick->release();
    }
    
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
    
    // 验证性能：平均每个tick处理时间应小于100微秒
    double avgTimePerTick = static_cast<double>(duration.count()) / TICK_COUNT;
    EXPECT_LT(avgTimePerTick, 100.0) << "Tick processing too slow: " << avgTimePerTick << " μs per tick";
    
    std::cout << "Tick processing performance: " << avgTimePerTick << " μs per tick" << std::endl;
}

/*!
 * \brief 测试引擎K线处理性能
 */
TEST_F(EnginePerformanceTest, TestBarProcessingPerformance)
{
    const int BAR_COUNT = 1000;
    
    auto start = std::chrono::high_resolution_clock::now();
    
    for (int i = 0; i < BAR_COUNT; ++i) {
        WTSBarStruct bar;
        bar.date = 20241201;
        bar.time = 202412010930 + i;
        bar.open = 4000.0 + i;
        bar.close = 4005.0 + i;
        bar.vol = 1000 + i;
        
        engine->on_bar("SHFE.rb2401", "m1", 1, &bar);
    }
    
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
    
    double avgTimePerBar = static_cast<double>(duration.count()) / BAR_COUNT;
    EXPECT_LT(avgTimePerBar, 1000.0) << "Bar processing too slow: " << avgTimePerBar << " μs per bar";
    
    std::cout << "Bar processing performance: " << avgTimePerBar << " μs per bar" << std::endl;
}

// ============================================================================
// 引擎集成测试
// ============================================================================

class EngineIntegrationTest : public ::testing::Test
{
protected:
    void SetUp() override {
        WTSLogger::init("test_logs/", true);
    }
    
    void TearDown() override {
        WTSLogger::stop();
    }
};

/*!
 * \brief 测试多引擎协同工作
 */
TEST_F(EngineIntegrationTest, TestMultiEngineCooperation)
{
    // 创建多个引擎实例
    auto ctaEngine = std::make_unique<WtCtaEngine>();
    auto hftEngine = std::make_unique<WtHftEngine>();
    auto selEngine = std::make_unique<WtSelEngine>();
    
    // 创建共享组件
    auto mockBdMgr = std::make_unique<NiceMock<MockBaseDataMgr>>();
    auto mockHotMgr = std::make_unique<NiceMock<MockHotMgr>>();
    auto dataMgr = std::make_unique<WtDtMgr>();
    auto notifier = std::make_unique<EventNotifier>();
    
    WTSVariant* config = WTSVariant::createObject();
    config->append("name", "integration_test", false);
    
    // 初始化所有引擎
    EXPECT_NO_THROW({
        ctaEngine->init(config, mockBdMgr.get(), dataMgr.get(), mockHotMgr.get(), notifier.get());
        hftEngine->init(config, mockBdMgr.get(), dataMgr.get(), mockHotMgr.get(), notifier.get());
        selEngine->init(config, mockBdMgr.get(), dataMgr.get(), mockHotMgr.get(), notifier.get());
    });
    
    // 测试同时处理数据
    WTSTickData* tick = WTSTickData::create("SHFE.rb2401");
    tick->setPrice(4000.0);
    tick->setVolume(100);
    
    EXPECT_NO_THROW({
        ctaEngine->on_tick("SHFE.rb2401", tick);
        hftEngine->on_tick("SHFE.rb2401", tick);
        selEngine->on_tick("SHFE.rb2401", tick);
    });
    
    tick->release();
    config->release();
}

/*!
 * \brief 测试引擎错误恢复能力
 */
TEST_F(EngineIntegrationTest, TestEngineErrorRecovery)
{
    auto engine = std::make_unique<TestableWtEngine>();
    auto mockBdMgr = std::make_unique<NiceMock<MockBaseDataMgr>>();
    auto mockHotMgr = std::make_unique<NiceMock<MockHotMgr>>();
    auto dataMgr = std::make_unique<WtDtMgr>();
    auto notifier = std::make_unique<EventNotifier>();
    
    WTSVariant* config = WTSVariant::createObject();
    config->append("name", "error_recovery_test", false);
    
    engine->init(config, mockBdMgr.get(), dataMgr.get(), mockHotMgr.get(), notifier.get());
    
    // 测试空指针处理
    EXPECT_NO_THROW({
        engine->on_tick("SHFE.rb2401", nullptr);
        engine->on_bar("SHFE.rb2401", "m1", 1, nullptr);
    });
    
    // 测试异常数据处理
    WTSTickData* invalidTick = WTSTickData::create("");  // 空代码
    if (invalidTick) {
        EXPECT_NO_THROW({
            engine->on_tick("", invalidTick);
        });
        invalidTick->release();
    }
    
    config->release();
}

// ============================================================================
// 主函数
// ============================================================================

int main(int argc, char** argv)
{
    ::testing::InitGoogleTest(&argc, argv);
    
    // 设置测试环境
    std::cout << "开始执行WonderTrader核心引擎综合测试..." << std::endl;
    
    int result = RUN_ALL_TESTS();
    
    std::cout << "\n=== 引擎测试总结 ===" << std::endl;
    std::cout << "✓ WtEngine基础引擎测试" << std::endl;
    std::cout << "✓ WtCtaEngine CTA引擎测试" << std::endl;
    std::cout << "✓ WtHftEngine HFT引擎测试" << std::endl;
    std::cout << "✓ WtSelEngine SEL引擎测试" << std::endl;
    std::cout << "✓ WtUftEngine UFT引擎测试" << std::endl;
    std::cout << "✓ 引擎性能基准测试" << std::endl;
    std::cout << "✓ 引擎集成测试" << std::endl;
    std::cout << "\n所有引擎测试完成！" << std::endl;
    
    return result;
}